package org.fang.controller;

import org.fang.common.PlatformResult;
import org.fang.pojo.CloudUser;
import org.fang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author forsake
 * @Description
 * @Date 17:21 2022/3/9
 **/
@RestController
@RequestMapping("/cloudUser")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    DiscoveryClient client;
    @RequestMapping("/add")
    public PlatformResult add(@RequestBody CloudUser user) {
        try {
            boolean add = userService.add(user);
        } catch (Exception e) {
            e.printStackTrace();
            return PlatformResult.failure(e.getMessage());
        }
        return PlatformResult.success();
    }
    @RequestMapping("/queryById/{id}")
    public PlatformResult queryById(@PathVariable("id") Integer id) {
        CloudUser cloudUser = null;
        try {
            cloudUser = userService.queryById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return PlatformResult.failure("查询错误");
        }
        return PlatformResult.success(cloudUser);
    }

    /**
     * 获取服务信息
     * @return
     */
    @GetMapping("/discovery")
    public PlatformResult discovery() {
        List<String> services = client.getServices();
        System.out.println(services);
        List<ServiceInstance> provider_8001 = client.getInstances("PROVIDER_8001");
        for (ServiceInstance serviceInstance : provider_8001) {
            System.out.println(serviceInstance.getHost());
            System.out.println(serviceInstance.getPort());
            System.out.println(serviceInstance.getServiceId());
        }
        return PlatformResult.success();
    }

}
